package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.atheima.apis.article.saveArticle;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleService;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.articleDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewSMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private WmNewSMapper wmNewSMapper;
    @Override
    //标明当前方法是异步方法
    @Async
    public void authActicle(Integer id) {
        //根据id查询文章
        WmNews wmNews = wmNewSMapper.selectById(id);
        //获取文章里面的文本和图片
        if (wmNews==null)
        {
            throw  new RuntimeException("文章不存在");
        }

        if (wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            //获取文章文本和图片
             Map<String,Object>  map=handleTextAndImages(wmNews);
             //通过敏感词汇库进行敏感词审核
            boolean content = handleSensitiveScan( map.get("content").toString(), wmNews);
            //这里使用的事本地的审核不花钱所以没有写死
            //content=true;
            if (!content)return;
            //文本审核，调用阿里云接口
            boolean isTextScan=handleTextScan(map.get("content"),wmNews);
            //这里没有申请阿里审核，所以没有使用远程的阿里审核，直接默认文本审核通过
            isTextScan=true;
            if(!isTextScan)return;

            boolean  isImageScan= handleImageScan((List<String>)map.get("images"),wmNews);
            //这里没有申请阿里审核，所以没有使用远程的阿里审核，直接图片默认审核通过
            isImageScan=true;
            if(!isImageScan) return;
            //如果图片和文本文本审核都通过的话修改审核状态
            if(content&&isTextScan&&isImageScan)
            {
                wmNews.setReason("审核成功");
            }
            //审核成功，保存app端文章信息
            ResponseResult responseResult=saveAppArticle(wmNews);


        }
    }
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    private boolean handleSensitiveScan(String content, WmNews wmNews)
    {
        boolean flag=true;


        //获取所有敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> collect = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(collect);
        //查看文章是否有敏感词汇
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size() >0){
            updateWmNews(wmNews,(short) 2,"当前文章中存在违规内容"+map);
            flag = false;
        }

        return flag;
    }
    @Autowired
private WmChannelMapper wmChannelMapper;
@Autowired
private WmUserMapper wmUserMapper;

@Autowired
private saveArticle saveArticle;

    /**
     * 保存文章信息
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {


        articleDto articledto=new articleDto();

        BeanUtils.copyProperties(wmNews,articledto);
        //设置下面图片布局
        articledto.setLayout(wmNews.getType());
        //根据频道id查询频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel!=null)
        {
            articledto.setChannelName(wmChannel.getName());
        }
        //封装作者信息
        articledto.setAuthorId(wmNews.getUserId().longValue());
        WmUser user = wmUserMapper.selectById(wmNews.getId());
        if (user!=null)
        {
            articledto.setAuthorName(user.getName());
        }
        //设置文章id
        if(wmNews.getArticleId()!=null)
        {
            articledto.setId(wmNews.getArticleId());
        }
        articledto.setCreatedTime(new Date());
        ResponseResult responseResult = saveArticle.saveArticle(articledto);
        return responseResult;
    }

    /**
     * 调用阿里图片审核方法
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {
        boolean flag=true;
        //先判断是否有图片，没有图片的话不用审核直接返回true就行
        if(images==null||images.size()==0)
        {
            return flag;
        }
        //集合里面的图片进行去重
      images = images.stream().distinct().collect(Collectors.toList());
        List<byte[]> imageList = new ArrayList<>();
        Tess4jClient tess4jClient=new Tess4jClient();
            for (String imagesLsit:images)
            {
                byte[] bytes = fileStorageService.downLoadFile(imagesLsit);

                try {
                    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
                    BufferedImage imageFile = ImageIO.read(in);
                    //识别图片的文字
                    String result = tess4jClient.doOCR(imageFile);

                    //审核是否包含自管理的敏感词
                    boolean isSensitive = handleSensitiveScan(result, wmNews);
                    if(!isSensitive){
                        return isSensitive;
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                imageList.add(bytes);
            }


        try {

            Map map = greenImageScan.imageScan(imageList);
            if (map.get("suggestion").equals("block"))
            {
                updateWmNews(wmNews,(short) 2,"图片审核不通过");
            }
            if (map.get("suggestion").equals("review"))
            {
                updateWmNews(wmNews,(short) 3,"图片人工审核中");
            }
        } catch (Exception e) {
            flag=false;
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 文本内容进行审核
     * @param content
     * @param wmNews
     * @return
     */
    @Autowired
    private GreenTextScan greenTextScan;
    private boolean handleTextScan(Object content, WmNews wmNews) {
        boolean  flag=true;
        if((wmNews.getTitle()+"-"+content).length() == 0){
            return flag;
        }
        try {
            Map map = greenTextScan.greeTextScan(wmNews.getContent() + "-" + content);
            if (map!=null)
            {
                //审核失败
                if (map.get("suggestion").equals("block"))
                {
                    flag=false;
                    updateWmNews(wmNews,(short)1,"审核不通过");

                }
                //需要人工审核
                if (map.get("suggestion").equals("review"))
                {
                    flag=false;
                    updateWmNews(wmNews,(short)3,"人工审核中");
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }


        return flag;
    }

    //根据审核结果修改数据库信息
    private void updateWmNews(WmNews wmNews, short i, String string) {
        wmNews.setStatus(i);
        wmNews.setReason(string);
        wmNewSMapper.updateById(wmNews);

    }

    /**
     * 获取文章纯文本和图片信息
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        StringBuffer stringBuffer=new StringBuffer();
        List<String> images=new ArrayList<>();
        //获取文本
        if(!StringUtils.isEmpty(wmNews.getContent()))
        {
            List<Map> textMap = JSONArray.parseArray(wmNews.getContent(), Map.class);
            for (Map map:textMap)
            {
                if (map.get("type").equals("text")) {
                    stringBuffer.append(map.get("value"));
                }
                if (map.get("type").equals("images"))
                    {
                    images.add((String) map.get("value"));
                }
            }
        }
        //提取文章中的首页图片

        if (!StringUtils.isEmpty(wmNews.getImages()))
        {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));

        }
        Map<String,Object> m=new HashMap<>();
        m.put("content",stringBuffer);
        m.put("images",images);

        return m;
    }
}
